package Reflect.demo02;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
    反射机制的执行效率测试
 */
public class Test01 {
    public static void main(String[] args) {
        Cat cat = new Cat();
//        m1();
//        m2();
//        m3();
    }

    //不使用反射调用方法
    public static void m1(){
        long start = System.currentTimeMillis();
        Cat cat = new Cat();
        for (int i = 0; i < 100000000; i++) {
            cat.sayHello();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
    }

    //使用反射调用方法
    public static void m2(){
        long start  = System.currentTimeMillis();
        Class<Cat> catClass = Cat.class;
        try {
            Cat cat = catClass.newInstance();
            Method method = catClass.getMethod("sayHello");
            for (int i = 0; i < 100000000; i++) {
                method.invoke(cat);
            }
            long end = System.currentTimeMillis();
            System.out.println(end-start);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    //使用反射调用方法(优化)
    public static void m3(){
        long start  = System.currentTimeMillis();
        Class<Cat> catClass = Cat.class;
        try {
            Cat cat = catClass.newInstance();
            Method method = catClass.getMethod("sayHello");
            method.setAccessible(true);
            for (int i = 0; i < 100000000; i++) {
                method.invoke(cat);
            }
            long end = System.currentTimeMillis();
            System.out.println(end-start);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
